package com.lingnan.blog.utils;

import com.lingnan.blog.entity.User;
import org.apache.shiro.crypto.RandomNumberGenerator;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;

/**
 * md5加盐加密工具类
 *
 * @author HeGuanChao
 */
public class Md5Util {
    private static RandomNumberGenerator generator = new SecureRandomNumberGenerator();
    /**
     * 基础散列算法
     */
    public static final String ALGORITHM_NAME = "md5";
    /**
     * 自定义散列次数
     */
    public static final int HASH_ITERATIONS = 1024;

    public static void encryptPassword(User user) {
        //随机字符串作为盐值
        user.setSalt(generator.nextBytes().toHex());
        String newPassword = new SimpleHash(ALGORITHM_NAME, user.getPassword(),
                ByteSource.Util.bytes(user.getSalt()), HASH_ITERATIONS).toHex();
        user.setPassword(newPassword);
    }
}
